<template>
  <view class="confirm-refuel-container">
    <!-- 顶部导航栏 (系统自带) -->
    <!-- uni-app 默认使用系统导航栏，无需额外组件 -->

    <!-- 警告信息 -->
    <uv-notice-bar bgColor="#FFFBE6" color="#FA3534" leftIcon="error-circle-fill" :text="warningText" mode="link"
      class="warning-bar"></uv-notice-bar>

    <!-- 主内容区域 - 卡片 -->
    <view class="main-card">
      <!-- 实际加油量 -->
      <view class="form-item">
        <text class="label required">实际加油量</text>
        <view class="input-group">
          <uv-input v-model="real_usage" placeholder="请输入用油量" type="digit" border="none" inputAlign="right"
            class="input-field" @input="onFuelAmountChange"></uv-input>
          <text class="unit">L(升)={{ convertedTons }}吨</text>
        </view>
      </view>
      <uv-line color="#F5F5F5"></uv-line>

      <!-- 实际金额 -->
      <view class="form-item">
        <text class="label required">实际金额</text>
        <view class="input-group">
          <uv-input v-model="actualAmount" placeholder="自动计算" type="digit" border="none" inputAlign="right" disabled
            class="input-field"></uv-input>
          <text class="unit">元</text>
        </view>
      </view>
      <uv-line color="#F5F5F5"></uv-line>

      <!-- 上传图片 -->
      <view class="form-item image-upload-item">
        <text class="label required">上传图片(最多上传20张)</text>
        <view class="image-upload-area">
          <view class="upload-placeholder" @click="chooseImage">
            <uv-icon name="plus" :size="40" color="#C0C4CC" class="plus-icon"></uv-icon>
          </view>
          <!-- 实际上传的图片列表 -->
          <view v-for="(image, index) in uploadedImages" :key="index" class="uploaded-image-wrapper">
            <image :src="image" mode="aspectFill" class="uploaded-image" @click="previewImage(index)" @longpress="onImageLongPress(index)"></image>

            <!-- 上传状态指示器 -->
            <view v-if="!uploadedImageUrls[index]" class="upload-status">
              <uv-icon name="loading" size="16" color="#FF6B35" class="loading-icon"></uv-icon>
              <text class="status-text">上传中</text>
            </view>

          </view>
        </view>
      </view>
    </view>

    <!-- 底部确认按钮 -->
    <view class="bottom-fixed-btn">
      <uv-button text="确认" type="primary" size="large" :custom-style="primaryBtn" @click="confirmOrder"></uv-button>
    </view>
  </view>
</template>

<script setup lang="ts">
// 获取页面参数：在 APP/H5/小程序端均推荐使用 onLoad 回调
import { onLoad } from '@dcloudio/uni-app'
import { ref, computed, watch, onMounted } from 'vue'
import { useRequest } from '@/api'
const { API_TIANXIEXL_LIST, API_MEMBER_INFO ,API_JIDAN_DETAIL_GET} = useRequest()
import { UserInfoManager } from '@/utils/userInfo'
// 页面参数
const orderId = ref('')

// 表单数据
const real_usage = ref('')
const actualAmount = ref('')
const uploadedImages = ref<string[]>([])
const uploadedImageUrls = ref<string[]>([])
const warningText = ref('本次加油量不可超过0升≈0吨')
// 提前声明，供下方 computed 使用
const userInfo = ref({})
const orderDetail = ref({})

// 油量到吨的转换比例 (100升 ≈ 1吨)
const FUEL_TO_TON_RATIO = 0.001

// 动态计算可加油最大升数： (余额+赠送余额) / (油价+运费)
const pricePerLiter = computed(() => {
  const price = Number((orderDetail.value as any)?.goods_price) || 0
  const freight = Number((orderDetail.value as any)?.goods_freight) || 0
  return price + freight
})

const availableBalance = computed(() => {
  const balance = Number((userInfo.value as any)?.balance) || 0
  const gift = Number((userInfo.value as any)?.giftbalance) || 0
  return balance + gift
})

const maxLiters = computed(() => {
  if (pricePerLiter.value <= 0) return 0
  const liters = Math.floor(availableBalance.value / pricePerLiter.value)
  return liters > 0 ? liters : 0
})

watch([pricePerLiter, availableBalance, maxLiters], () => {
  const limit = Number(maxLiters.value) || 0
  const tons = (limit * FUEL_TO_TON_RATIO).toFixed(2)
  warningText.value = `本次加油量不可超过${limit}升≈${tons}吨`
}, { immediate: true })

// 计算转换后的吨数
const convertedTons = computed(() => {
  const amount = parseFloat(real_usage.value)
  if (!isNaN(amount) && amount > 0) {
    return (amount * FUEL_TO_TON_RATIO).toFixed(2)
  }
  return '0'
})

// 折扣（百分比），默认 100% 不打折
const discountFactor = computed(() => {
  const d = Number((userInfo.value as any)?.discount)
  if (!isFinite(d) || d <= 0) return 1
  return d / 100
})

// 按公式计算实际金额：(goods_price + goods_freight) * real_usage * (discount/100)
watch([() => real_usage.value, pricePerLiter, discountFactor], () => {
  const liters = parseFloat(real_usage.value)
  const price = Number(pricePerLiter.value)
  const disc = Number(discountFactor.value)
  if (!isNaN(liters) && liters > 0 && price > 0 && isFinite(disc)) {
    actualAmount.value = (liters * price * disc).toFixed(2)
  } else {
    actualAmount.value = ''
  }
})

const primaryBtn = {
  width: '100%',
  height: '88rpx',
  borderRadius: '48rpx',
  backgroundColor: '#FF6B35',
  color: '#fff',
  fontSize: '32rpx',
  fontWeight: '600'
}


onLoad((options: Record<string, any>) => {
  const id = options?.id ?? options?.orderId
  if (id) {
    try {
      orderId.value = decodeURIComponent(String(id))
    } catch {
      orderId.value = String(id)
    }
  }
})

// 加油量变化处理
const onFuelAmountChange = (value: string) => {
  const amount = parseFloat(value)
  const limit = maxLiters.value
  if (!isNaN(amount) && limit > 0 && amount > limit) {
    uni.showToast({
      title: `加油量不能超过${limit}升`,
      icon: 'none'
    })
    real_usage.value = String(limit)
  }
}

// 选择图片
const chooseImage = () => {
  const remainingCount = 20 - uploadedImages.value.length
  if (remainingCount <= 0) {
    uni.showToast({
      title: '最多只能上传20张图片',
      icon: 'none'
    })
    return
  }

  uni.chooseImage({
    count: remainingCount,
    sizeType: ['original', 'compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      const tempFilePaths = res.tempFilePaths
      // 先添加到临时图片列表
      uploadedImages.value = [...uploadedImages.value, ...tempFilePaths].slice(0, 20)

      if (Array.isArray(tempFilePaths)) {
        tempFilePaths.forEach((filePath) => {
          uploadFile(filePath)
        })
      }
    },
    fail: (err) => {
      console.error('选择图片失败', err)
      uni.showToast({
        title: '选择图片失败',
        icon: 'none'
      })
    }
  })
}

// 上传单个文件
const uploadFile = async (filePath: string) => {
  uni.showLoading({ title: '上传中...' })
  try {
    const uploadRes = await uni.uploadFile({
      url: import.meta.env.VITE_APP_API_BASEURL + '/api/index/upload',
      filePath: filePath,
      name: 'file',
      formData: {
        type: 'order_refuel' // 文件类型标识
      },
      success: (res) => {
        try {
          const data = JSON.parse(res.data)
          console.log(data)
          if (data.code === 1) {
            // 上传成功，将返回的URL添加到已上传列表
            uploadedImageUrls.value.push(data.data.fullurl)
            uni.showToast({
              title: '上传成功',
              icon: 'success'
            })
          } else {
            uni.showToast({
              title: data.msg || '上传失败',
              icon: 'none'
            })
          }
        } catch (e) {
          console.error('解析上传响应失败:', e)
          uni.showToast({
            title: '上传失败',
            icon: 'none'
          })
        }
      },
      fail: (err) => {
        console.error('上传失败:', err)
        uni.showToast({
          title: '上传失败',
          icon: 'none'
        })
      }
    })
  } catch (error) {
    console.error('上传异常:', error)
    uni.showToast({
      title: '上传异常',
      icon: 'none'
    })
  } finally {
    uni.hideLoading()
  }
}

// 删除图片
const deleteImage = (index: number) => {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除这张图片吗？',
    success: (res) => {
      if (res.confirm) {
        // 同时删除临时图片和已上传的图片
        uploadedImages.value.splice(index, 1)
        uploadedImageUrls.value.splice(index, 1)
        uni.showToast({
          title: '删除成功',
          icon: 'success'
        })
      }
    }
  })
}

// 预览图片（支持放大缩小）
const previewImage = (index: number) => {
  // 优先使用已上传后的完整URL，否则回退为本地临时路径
  const urls = uploadedImages.value.map((local, i) => uploadedImageUrls.value[i] || local)
  if (!urls.length) return
  uni.previewImage({
    current: index,
    urls,
    indicator: 'number',
    loop: true
  })
}

// 长按图片弹出操作菜单（预览/删除）
const onImageLongPress = (index: number) => {
  uni.showActionSheet({
    itemList: ['预览', '删除'],
    success: (res) => {
      if (res.tapIndex === 0) {
        previewImage(index)
      } else if (res.tapIndex === 1) {
        deleteImage(index)
      }
    }
  })
}

// 确认订单
const confirmOrder = async () => {
  // 表单验证
  if (!real_usage.value || parseFloat(real_usage.value) <= 0) {
    uni.showToast({
      title: '请输入实际加油量',
      icon: 'none'
    })
    return
  }

  if (maxLiters && maxLiters.value > 0 && parseFloat(real_usage.value) > maxLiters.value) {
    uni.showToast({
      title: `加油量不可超过${maxLiters.value}升`,
      icon: 'none'
    })
    return
  }

  if (uploadedImageUrls.value.length === 0) {
    uni.showToast({
      title: '请上传图片',
      icon: 'none'
    })
    return
  }
  const params = {
    isdriver: UserInfoManager.lastrole(),
    id: orderId.value,
    voucher: uploadedImageUrls.value.join(','),
    real_usage: real_usage.value
  }
  const res = await API_TIANXIEXL_LIST(params)
 
  if (res.code == 1) {
    uni.showToast({ title: '操作成功', icon: 'success' })
    setTimeout(() => {
      uni.$emit('refOrderList')
      setTimeout(() => {
        uni.navigateBack()
      }, 100)
    }, 500)
  }
}
const initFormData = async () => {
  const params = {
    isdriver: UserInfoManager.lastrole()
  }
  const res = await API_MEMBER_INFO(params)
  if (res.code === 1) {
    userInfo.value = res.data
  }
}
const getOrderDetail = async () => {
  
  if (!orderId.value) {
    uni.showToast({
      title: '订单ID不能为空',
      icon: 'none'
    })
    return
  }

  try {
    const params = {
      id: orderId.value,
      isdriver: UserInfoManager.lastrole()
    }
    const res = await API_JIDAN_DETAIL_GET(params)
    if (res.code === 1) {
      orderDetail.value = res.data
     
    }
  } catch (error) {
    
  } finally {
    
  }
}
// 页面加载时获取参数和详情
onMounted(() => {
  initFormData()

  getOrderDetail()
})
</script>

<style lang="scss" scoped>
.confirm-refuel-container {
  background-color: #f6f7f9;
  min-height: 100vh;
  padding-bottom: 120rpx;
  /* 留出底部按钮的空间 */
}

.warning-bar {
  margin-bottom: 20rpx;
}

.main-card {
  background-color: #fff;
  margin: 0 24rpx;
  border-radius: 16rpx;
  padding: 0 24rpx;
  box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.06);
}

.form-item {
  display: flex;
  flex-direction: column;
  padding: 30rpx 0;

  .label {
    font-size: 30rpx;
    color: #333;
    margin-bottom: 20rpx;
    font-weight: 500;

    &.required::before {
      content: '*';
      color: #fa3534;
      margin-right: 8rpx;
    }
  }

  .input-group {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;

    .input-field {
      flex: 1;
      font-size: 32rpx;
      color: #333;

      // 覆盖uv-input默认样式
      :deep(.uv-input__content__field-wrapper__field) {
        height: auto !important;
        min-height: 40rpx;
        padding: 0 !important;
      }
    }

    .unit {
      font-size: 28rpx;
      color: #999;
      margin-left: 20rpx;
      white-space: nowrap;
    }
  }
}

.image-upload-item {
  .image-upload-area {
    display: flex;
    flex-wrap: wrap;
    gap: 20rpx; // 图片之间的间距

    .upload-placeholder {
      width: 160rpx;
      height: 160rpx;
      background-color: #f7f7f7;
      border-radius: 8rpx;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      position: relative;
      border: 2rpx dashed #e0e0e0;
      cursor: pointer;
      transition: all 0.3s ease;

      &:active {
        background-color: #f0f0f0;
        transform: scale(0.98);
      }

      .plus-icon {
        position: absolute;
        bottom: 10rpx;
        right: 10rpx;
      }
    }

    .uploaded-image-wrapper {
      position: relative;
      width: 160rpx;
      height: 160rpx;
      border-radius: 8rpx;
      overflow: hidden;
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);

      .uploaded-image {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }

      .delete-image-icon {
        position: absolute;
        top: 8rpx;
        right: 8rpx;
        background-color: rgba(255, 255, 255, 0.9);
        border-radius: 50%;
        padding: 4rpx;
        z-index: 3;
        box-shadow: 0 2rpx 6rpx rgba(0,0,0,0.12);
        border: 1rpx solid rgba(0,0,0,0.06);
        cursor: pointer;
        transition: all 0.3s ease;

        &:active {
          transform: scale(1.1);
        }
      }

      .upload-status {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: rgba(0, 0, 0, 0.6);
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        border-radius: 8rpx;
        z-index: 2;

        .loading-icon {
          animation: rotate 1s linear infinite;
          margin-bottom: 8rpx;
        }

        .status-text {
          font-size: 20rpx;
          color: #fff;
        }
      }

      @keyframes rotate {
        from {
          transform: rotate(0deg);
        }

        to {
          transform: rotate(360deg);
        }
      }
    }
  }
}

.bottom-fixed-btn {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx 24rpx calc(20rpx + env(safe-area-inset-bottom));
  background-color: #fff;
  box-shadow: 0 -2rpx 12rpx rgba(0, 0, 0, 0.06);
  z-index: 10;
}
</style>
